// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  
  // 确保请求来自微信环境
  if (!wxContext.OPENID) {
    return {
      success: false,
      error: '非法请求，缺少OpenID'
    }
  }
  
  try {
    const { code, userInfo } = event
    
    // 获取用户的openid
    const openid = wxContext.OPENID
    const unionid = wxContext.UNIONID // 如果用户有关联的unionid
    
    // 验证请求数据
    if (!userInfo || !userInfo.name) {
      return {
        success: false,
        error: '用户信息不完整'
      }
    }
    
    // 安全检查：防止角色欺骗
    const validRoles = ['chef', 'guest']
    if (!validRoles.includes(userInfo.role)) {
      userInfo.role = 'guest' // 默认为guest角色
    }
    
    // 查找或创建用户
    let user = await db.collection('users')
      .where({
        openid: openid
      })
      .get()
    
    const now = new Date()
    
    if (user.data.length === 0) {
      // 创建新用户
      const newUser = {
        openid: openid,
        unionid: unionid || '',
        name: userInfo.name,
        role: userInfo.role || 'guest',
        points: 0,
        avatar: userInfo.avatar || '',
        createdAt: now,
        updatedAt: now,
        lastLogin: now,
        loginCount: 1,
        status: 'active'
      }
      
      // 记录登录IP和设备信息（如果有）
      if (event.clientInfo) {
        newUser.clientInfo = event.clientInfo
      }
      
      try {
        const result = await db.collection('users').add({
          data: newUser
        })
        
        // 记录用户创建日志
        await db.collection('user_logs').add({
          data: {
            userId: result._id,
            action: 'create',
            details: '用户创建',
            createdAt: now
          }
        })
        
        return {
          success: true,
          data: {
            user: {
              id: result._id,
              ...newUser
            },
            isNewUser: true,
            sessionId: generateSessionId(result._id, openid)
          }
        }
      } catch (dbError) {
        console.error('创建用户失败:', dbError)
        return {
          success: false,
          error: '创建用户失败'
        }
      }
    } else {
      // 更新现有用户信息
      const existingUser = user.data[0]
      
      // 检查用户状态
      if (existingUser.status === 'banned') {
        return {
          success: false,
          error: '账号已被禁用'
        }
      }
      
      // 准备更新数据
      const updateData = {
        name: userInfo.name,
        avatar: userInfo.avatar || existingUser.avatar,
        updatedAt: now,
        lastLogin: now,
        loginCount: _.inc(1)
      }
      
      // 记录登录IP和设备信息（如果有）
      if (event.clientInfo) {
        updateData.clientInfo = event.clientInfo
      }
      
      try {
        await db.collection('users').doc(existingUser._id).update({
          data: updateData
        })
        
        // 记录用户登录日志
        await db.collection('user_logs').add({
          data: {
            userId: existingUser._id,
            action: 'login',
            details: '用户登录',
            createdAt: now
          }
        })
        
        // 返回用户信息（不包含敏感字段）
        const userResponse = {
          id: existingUser._id,
          name: userInfo.name,
          role: existingUser.role,
          points: existingUser.points,
          avatar: userInfo.avatar || existingUser.avatar,
          createdAt: existingUser.createdAt,
          updatedAt: now
        }
        
        return {
          success: true,
          data: {
            user: userResponse,
            isNewUser: false,
            sessionId: generateSessionId(existingUser._id, openid)
          }
        }
      } catch (dbError) {
        console.error('更新用户信息失败:', dbError)
        return {
          success: false,
          error: '更新用户信息失败'
        }
      }
    }
  } catch (error) {
    console.error('登录云函数执行失败:', error)
    return {
      success: false,
      error: '登录处理失败'
    }
  }
}

/**
 * 生成会话ID
 * @param {string} userId 用户ID
 * @param {string} openid 微信OpenID
 * @returns {string} 会话ID
 */
function generateSessionId(userId, openid) {
  const timestamp = Date.now()
  const random = Math.random().toString(36).substring(2, 15)
  return `${userId}_${timestamp}_${random}`
} 